<route lang="json5">
{
  style: {
    navigationBarTitleText: 'Rental Records',
    enablePullDownRefresh: true, // 启用下拉刷新
    backgroundColor: '#f5f5f5', // 设置背景色，优化视觉效果
  },
}
</route>

<template>
  <view class="records-container">
    <wd-tabs v-model="activeTab" @change="handleTabChange">
      <wd-tab title="Current" name="current">
        <record-list
          :records="activeRecords"
          :loading="loading"
          status="active"
          empty-text="No active rentals"
          @refresh="fetchRecords"
          @cancel="handleCancel"
        />
      </wd-tab>

      <wd-tab title="Waiting" name="waiting">
        <record-list
          :records="waitingRecords"
          :loading="loading"
          status="waiting"
          empty-text="No waiting rentals"
          @refresh="fetchRecords"
          @cancel="handleCancel"
        />
      </wd-tab>

      <wd-tab title="History" name="history">
        <record-list
          :records="historyRecords"
          :loading="loading"
          status="history"
          empty-text="No rental history"
          @refresh="fetchRecords"
        />
      </wd-tab>
    </wd-tabs>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { getRentalRecords, cancelRental } from '@/service/rent'
import RecordList from './components/RecordList.vue'

const activeTab = ref('current')
const records = ref([])
const loading = ref(false)

// 根据状态分类记录
const activeRecords = computed(() => records.value.filter((r) => r.status === 'active'))
const waitingRecords = computed(() => records.value.filter((r) => r.status === 'waiting'))
const historyRecords = computed(() =>
  records.value.filter((r) => ['completed', 'cancelled'].includes(r.status)),
)

// 获取租赁记录
const fetchRecords = async (force = true) => {
  if (loading.value && !force) return

  loading.value = true
  try {
    const res = await getRentalRecords()
    if (res.code === 200) {
      records.value = res.data
    } else {
      throw new Error(res.msg)
    }
  } catch (error) {
    console.error('Failed to load records:', error)
    uni.showModal({
      title: 'Connection Error',
      content: 'Failed to load records. Would you like to try again?',
      confirmText: 'Retry',
      success: (res) => {
        if (res.confirm) {
          fetchRecords()
        }
      },
    })
  } finally {
    loading.value = false
  }
}

// 处理取消预订
const handleCancel = async (record: any) => {
  uni.showModal({
    title: 'Cancel Reservation',
    content: `Are you sure to cancel the reservation for Scooter #${record.scooterId}?`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await cancelRental(record.id)
          uni.showToast({
            title: 'Cancelled successfully',
            icon: 'success',
          })
          fetchRecords() // 重新加载记录
        } catch (error) {
          uni.showToast({
            title: 'Failed to cancel',
            icon: 'none',
          })
        }
      }
    },
  })
}

// 只保留下拉刷新
onPullDownRefresh(() => {
  fetchRecords().finally(() => {
    uni.stopPullDownRefresh()
  })
})

// 添加下拉刷新处理函数
onPullDownRefresh(async () => {
  try {
    await fetchRecords()
  } finally {
    // 完成下拉刷新
    uni.stopPullDownRefresh()
  }
})

// 添加选项卡切换处理函数
const handleTabChange = () => {
  // 切换标签页时刷新数据
  fetchRecords()
}

onMounted(() => {
  fetchRecords()
})
</script>

<style lang="scss">
.records-container {
  min-height: 100vh;
  background: #f5f5f5;
}

.records-list {
  padding: 16px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
  color: #999;
}

.record-card {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    .scooter-id {
      font-size: 16px;
      font-weight: bold;
    }
  }

  .details {
    .info-row {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;

      .label {
        color: #666;
      }

      .value {
        color: #333;
        &.price {
          color: #f60;
          font-weight: bold;
        }
      }
    }
  }
}

.loading-state {
  text-align: center;
  padding: 40px 0;
  color: #666;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}
</style>
